import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Menu } from "antd";
import React, { useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";

type MenuItem = Required<MenuProps>["items"][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const items: MenuItem[] = [
  getItem("Option 1", "/page1", <PieChartOutlined />),
  getItem("Option 2", "/page2", <DesktopOutlined />),
  getItem("User", "sub1", <UserOutlined />, [
    getItem("Tom", "/page3/page301"),
    getItem("Bill", "/page3/page302"),
    getItem("Alex", "5"),
  ]),
  getItem("Team", "sub2", <TeamOutlined />, [
    getItem("Team 1", "6"),
    getItem("Team 2", "8"),
  ]),
  getItem("Files", "9", <FileOutlined />),
];

const myMenu: React.FC = () => {
  const navigateTo = useNavigate();
  const currentRoute = useLocation();

  const menuClick = (e: { key: string }) => {
    console.log("点击了", e.key);

    //点击跳转到对应的路由    编程时导航跳转，利用到hook
    navigateTo(e.key);
  };

  //拿着currentRoute.pathname跟items数组的每一项children的key值进行对比，如果找到了，就要他上一级的key
  //这个key给到openKeys数组的元素，作为初始值

  let firstOpenKey: string = "";
  //在这里进行对比
  function findKey(obj: { key: string }) {
    return obj.key === currentRoute.pathname;
  }

  //对比的是多个children
  for (let i = 0; i < items.length; i++) {
    //判断找到找不到children
    if (
      items[i]["children"] &&
      items[i]["children"].length > 1 &&
      items[i]["children"].find(findKey)
    ) {
      firstOpenKey = items[i].key as string;
      break;
    }
  }
  // items[?]["children"].find(findKey); //这结果如果找到拿到的是一个对象，转布尔值就是true

  //设置展开项的初始值
  const [openKeys, setOpenKeys] = useState([firstOpenKey]);
  const handleOpenChange = (keys: string[]) => {
    //什么时候执行这个函数里面的代码？展开和回收某项菜单的时候执行这里的代码
    // console.log(keys); //keys是一个数组，记录了当前哪一项是展开的（用key来记录）
    //把这个数组修改成最后一项，因为只要一项是展开的，就是我刚刚点击的这一项
    setOpenKeys([keys[keys.length - 1]]);
  };

  return (
    <Menu
      theme="dark"
      // defaultSelectedKeys 表示当前样式所在选中项的key
      defaultSelectedKeys={[currentRoute.pathname]}
      mode="inline"
      //菜单项数据
      items={items}
      onClick={menuClick}
      //某项菜单展开和回收的事件
      onOpenChange={handleOpenChange}
      //当前菜单展开项的数组
      openKeys={openKeys}
    />
  );
};

export default myMenu;
